package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-gin-admin/model"
	"github.com/go-gin-admin/util"
	"net/http"
	"time"
)

// 增加岗位
func AddJob(c *gin.Context) {
	var jobData model.Job
	if err := c.BindWith(&jobData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	local := time.Now().Local()
	jobData.CreateTime = local
	jobData.UpdateTime = local
	insertId, err := jobData.Add()
	if err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("创建失败"))
		return
	}
	m := make(map[string]interface{})
	m["insertId"] = insertId
	c.JSON(http.StatusOK, new(util.Response).Ok("创建成功", m))
}

// 获取岗位
func GetJobList(c *gin.Context) {
	var jobData model.Job
	// 获取参数
	pageSize, _ := util.StringToInt64(c.DefaultQuery("pageSize", "10"))
	pageIndex, _ := util.StringToInt64(c.DefaultQuery("pageIndex", "1"))
	m, err := jobData.GetList(pageIndex, pageSize)
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", m))
}

// 更新岗位
func UpdateJob(c *gin.Context) {
	var jobData model.Job
	if err := c.BindWith(&jobData, binding.JSON); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("参数解析错误"))
		return
	}
	jobData.UpdateTime = time.Now().Local()
	if err := jobData.Update(); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("更新失败"))
		return
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("更新成功", nil))
}

// 删除岗位
func DeleteJob(c *gin.Context) {
	var jobData model.Job
	// 获取id
	id, _ := util.StringToInt64(c.Param("id"))
	if err := jobData.Remove(id); err != nil {
		c.JSON(http.StatusOK, new(util.Response).Err("删除失败"))
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("删除成功", nil))
}

func GetJobAllList(c *gin.Context) {
	var jobData model.Job
	data, err := jobData.GetAllList()
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusOK, new(util.Response).Ok("", data))
}
